<template>
  <!-- 新增实物商品 -->
  <div class="content">
    <h2>新增商品</h2>
    <div class="u-form-box">
      <el-form
        :model="ruleForm"
        :rules="rules"
        ref="ruleForm"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-row>
          <el-col :span="12">
            <el-form-item label="商品名称" prop="goodsName">
              <el-input
                v-model="ruleForm.goodsName"
                placeholder="请输入商品名称"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="副标题" prop="goodsDesc">
              <el-input
                v-model="ruleForm.goodsDesc"
                placeholder="请输入副标题"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="视频" prop="goodsVideoUrl">
          <el-upload
            class="avatar-uploader"
            action="https://jsonplaceholder.typicode.com/posts/"
            :show-file-list="false"
            :http-request="uploadVideo"
            :before-upload="beforeVideoUpload"
          >
            <video
              v-if="ruleForm.goodsVideoUrl"
              :src="ruleForm.goodsVideoUrl"
              controls="controls"
              class="video"
            />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
          <el-progress
            :percentage="percentage"
            v-show="showRentPrise"
            control
          ></el-progress>
          <p class="u-img-text">请上传100M以内的视频</p>
        </el-form-item>
        <el-form-item label="轮播图" prop="mainPic" class="clearfix">
          <el-radio-group v-model="ruleForm.mainPic" class="fl margin-right30">
            <el-radio
              v-for="(poster, index) in posters"
              :label="poster.img"
              :key="index"
            >
              <img :src="poster.img" width="150" height="150" />
              <span class="el-upload-delete" @click="handleRemove(index)"
                >x</span
              >
            </el-radio>
          </el-radio-group>
          <el-upload
            class="avatar-uploader"
            :action="url"
            :show-file-list="false"
            :before-upload="beforeAvatarUpload"
            :http-request="uploadAvatarImg"
          >
            <i class="el-icon-plus avatar-uploader-icon"></i>
            <div slot="tip" class="el-upload__tip">
              请上传jpg.gif.png格式的图片，图片尺寸540*353px
            </div>
          </el-upload>
        </el-form-item>
        <el-row>
          <el-col :span="12">
            <el-form-item label="采购成本" prop="purchaseCost">
              <el-input
                v-model="ruleForm.purchaseCost"
                placeholder="请输入采购成本"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="库存" prop="stockCount">
              <el-input
                v-model="ruleForm.stockCount"
                placeholder="请输入库存"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="所需金币" prop="exchangeCoins">
              <el-input
                v-model="ruleForm.exchangeCoins"
                placeholder="请输入所需金币"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="兑换基数" prop="buyRadix">
              <el-input
                v-model="ruleForm.buyRadix"
                placeholder="请输入兑换基数"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="详情页" prop="deatilPage">
          <el-upload
            class="avatar-uploader"
            :action="url"
            :show-file-list="false"
            :http-request="uploadImg"
            :before-upload="beforeAvatarUpload"
          >
            <img
              v-if="ruleForm.deatilPage"
              :src="ruleForm.deatilPage"
              class="avatar"
            />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            <div slot="tip" class="el-upload__tip">
              请上传jpg.gif.png格式的图片，图片宽度750px。
            </div>
          </el-upload>
          <el-checkbox v-model="ruleForm.isHot">设为热门兑换</el-checkbox>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitForm('ruleForm')"
            >保存</el-button
          >
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>
<script>
import { addGood, getGoodById, updateGood } from '@/api/goods.js'
import { ossUpload } from '@/api/api.js'
import { ossUploadFile } from '@/api/mixins'
export default {
  data () {
    var validateNum = (rule, value, callback) => {
      if (!/^([1-9]\d*|[0]{1,1})$/.test(value)) {
        callback('请输入正整数！')
      } else {
        callback()
      }
    }
    return {
      good_id: '',
      url: '',
      posters: [],
      percentage: 0,
      ruleForm: {
        goodsName: '',
        goodsDesc: '',
        goodsVideoUrl: '',
        mainPic: '',
        purchaseCost: '',
        stockCount: '',
        exchangeCoins: '',
        buyRadix: '',
        deatilPage: '',
        isHot: true
      },
      showRentPrise: false,
      rules: {
        goodsName: [
          { required: true, message: '请输入商品名称', trigger: 'blur' },
          { min: 2, max: 30, message: '长度在 2 到 30 个字符', trigger: 'blur' }
        ],
        mainPic: [{ required: true, message: '请上传轮播图', trigger: 'blur' }],
        purchaseCost: [
          {
            required: true,
            message: '请输入采购成本',
            trigger: 'blur'
          }
        ],
        stockCount: [
          { required: true, message: '请输入库存', trigger: 'blur' },
          { validator: validateNum, trigger: 'blur' }
        ],
        exchangeCoins: [
          { required: true, message: '请输入所需金币', trigger: 'blur' },
          { validator: validateNum, trigger: 'blur' }
        ],
        deatilPage: [
          { required: true, message: '请选择详情页', trigger: 'blur' }
        ]
      }
    }
  },
  activated () {
    this.good_id = this.$route.query.id
    this.posters = []
    this.$refs['ruleForm'].resetFields()
    if (this.good_id) {
      this.getGoodById()
    } else {
      this.ruleForm = {
        goodsName: '',
        goodsDesc: '',
        goodsVideoUrl: '',
        mainPic: '',
        purchaseCost: '',
        stockCount: '',
        exchangeCoins: '',
        buyRadix: '',
        deatilPage: '',
        isHot: true
      }
    }
  },
  methods: {
    async getGoodById () {
      let res = await getGoodById({ id: this.good_id })
      if (res[0]) {
        return
      }
      if (res[1].code == 0) {
        this.ruleForm = res[1].targetGoods
        if (this.ruleForm.mainPic) {
          this.posters.push({ img: this.ruleForm.mainPic })
          if (this.ruleForm.goodsPics) {
            let arr = this.ruleForm.goodsPics.split(',')
            arr.forEach(ele => {
              this.posters.push({ img: ele })
            })
          }
        }
      }
    },
    progress (percentage, checkpoint, res) {
      this.percentage = parseInt(percentage * 100)
    },
    handleRemove (index) {
      this.posters.splice(index, 1)
      this.ruleForm.mainPic =
        this.posters && this.posters.length ? this.posters[0].img : ''
    },
    async uploadImg (e) {
      let formData = new FormData()
      formData.append('file', e.file)
      let res = await ossUpload(formData, 'POSTER_COVER')
      if (res[0]) {
        return
      }
      this.ruleForm.deatilPage = res[1].data.url
    },
    async uploadVideo (e) {
      let formData = new FormData()
      formData.append('file', e.file)
      let url = await ossUploadFile(this, e, 'STUDENGT_PORTRAIT')
      this.ruleForm.goodsVideoUrl = url
      console.log(222222, this.ruleForm.goodsVideoUrl)
    },
    async uploadAvatarImg (e) {
      let formData = new FormData()
      formData.append('file', e.file)
      let res = await ossUpload(formData, 'POSTER_COVER')
      if (res[0]) {
        return
      }
      this.posters.unshift({ img: res[1].data.url })
      if (this.posters && this.posters.length > 4) {
        this.posters.pop()
      }
      this.ruleForm.mainPic = this.posters[0].img
    },
    beforeAvatarUpload (file) {
      const isJPG =
        file.type === 'image/jpeg' ||
        file.type === 'image/png' ||
        file.type == 'image/gif' ||
        file.type == 'image/jpg'
      const isLt5M = file.size / 1024 / 1024 < 5
      if (!isLt5M) {
        this.$message.error('上传头像图片大小不能超过5MB!')
      }
      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG、PNG 格式以及gif格式!')
      }
      return isLt5M
    },
    beforeVideoUpload (file) {
      const isLt100M = file.size / 1024 / 1024 < 100
      if (!isLt100M) {
        this.$message.error('上传视频大小不能超过 100MB!')
      }
      return isLt100M
    },
    submitForm (formName) {
      this.$refs[formName].validate(async valid => {
        if (valid) {
          // 判断是新增还是编辑
          let arr = [],
            goodsPics = ''
          if (this.posters && this.posters.length) {
            this.posters.forEach(ele => {
              if (ele.img != this.ruleForm.mainPic) {
                arr.push(ele.img)
              }
            })
            console.log('arr', arr)
            goodsPics = arr.join(',')
          }
          let arg = {
            goodsName: this.ruleForm.goodsName,
            goodsDesc: this.ruleForm.goodsDesc,
            purchaseCost: Number(this.ruleForm.purchaseCost),
            stockCount: Number(this.ruleForm.stockCount),
            exchangeCoins: Number(this.ruleForm.exchangeCoins),
            buyRadix: Number(this.ruleForm.buyRadix),
            deatilPage: this.ruleForm.deatilPage,
            mainPic: this.ruleForm.mainPic,
            goodsPics: goodsPics,
            goodsVideoUrl: this.ruleForm.goodsVideoUrl,
            isHot: this.ruleForm.isHot ? 1 : 0
          }
          if (this.good_id) {
            let res = await updateGood({
              id: this.good_id,
              ...arg
            })
            if (res[0]) {
              return
            }
            if (res[1].code == 0) {
              this.$message.success('编辑成功！')
              this.$router.push({ name: 'entity-administration' })
            }
          } else {
            let res = await addGood({
              operator: localStorage.getItem('sys_user_id'),
              ...arg
            })
            if (res[0]) {
              return
            }
            if (res[1].code == 0) {
              this.$message.success('新增成功！')
              this.$router.push({ name: 'entity-administration' })
            }
          }
        } else {
          console.log('error submit!!')
          return false
        }
      })
    }
  }
}
</script>
<style scoped>
h2 {
  padding-left: 20px;
}
.u-form-box {
  /* width: 1000px; */
  padding-bottom: 50px;
}
.video {
  width: 200px;
  height: 200px;
}
.u-form-item-rate {
  padding-top: 9px;
}
.u-text-right {
  text-align: right;
}
.u-img-text {
  margin-bottom: 10px;
}
.el-radio {
  position: relative;
}
.el-upload-delete {
  position: absolute;
  top: 10px;
  right: 10px;
}
</style>
